var layer = parent.layer;
var templateParams = {
    btnTools:[]
};

var columnsSetting = [];

var eventList = {
    '#expand-all-true':function(){
        if (zTreeObj != null) {
            zTreeObj.expandAll(true);
        }
    },
    '#expand-all-false':function(){
        if (zTreeObj != null) {
            zTreeObj.expandAll(false);
        }
    },
    '#refresh-tree': function(){
        refreshZtree();
    }
};

var mySetting = {
    eventList:eventList,
    userDefaultRender:false,
    userDefaultTemplate:false,
    customCallBack:function(params){
        //$('#treeDemo').scrollTop( $('#treeDemo')[0].scrollHeight);
        refreshZtree();
    },
    editPage:{

    }
};


$(function(){
    publish.renderParams = $.extend(true,publish.renderParams, mySetting);
    publish.init();
});

/*****************************************************************************************/
var zTreeObj;
var demoIframe;
var beforeNodeName;
var currentNode;
var setting = {
    view: {
        dblClickExpand: false,
        showLine: true,
        selectedMulti: false,
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom
    },
    data: {
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "parent_node_id",
            rootPId: 1
        },
        key: {
            name:"node_name"
        }
    },
    edit:{
        enable: true,
        showRemoveBtn: true,
        showRenameBtn: true,
        removeTitle:"删除节点",
        renameTitle: "修改名称",
        drag:{
            isCopy: false,
            isMove: false
        }
    },
    callback: {
        beforeClick: function(treeId, treeNode) {
            if (filter(treeNode)) {
                parent.$("#element-frame").attr("src","webElement.html?node_id=" + treeNode.id + '&node_name=' + treeNode.node_name);
                currentNode = treeNode;
                return true;
            }
        },
        beforeEditName:beforeEditName,
        beforeRemove:beforeRemove,
        onRename:onRename,
        onRemove:onRemove
    }
};


/**
 * 鼠标移动到节点上在显示增加的按钮
 * @param treeId
 * @param treeNode
 * @returns
 */
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length>0) return;

    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='增加节点' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind('click', function(event) {
            event.stopPropagation();
            addChildElement(this, treeId, treeNode);
        }
    );
}

/**
 * 增加子节点的操作
 * @returns
 */
function addChildElement(domObj, treeId, treeNode) {
    //判断当前节点类型
    if (treeNode.node_level == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.PAGE.value) {
        layer.msg('不能在此节点下创建子节点！', {time: 1400});
        return;
    }

    let createNodeLevel = GLOBAL_PARAM.ELEMENT_NODE_LEVEL.PAGE;
    if (treeNode.node_level == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.ROOT.value) {
        createNodeLevel = GLOBAL_PARAM.ELEMENT_NODE_LEVEL.SYSTEM;
    }

    layer.confirm('确定在  ' + treeNode.node_name + ' 下创建类型为 [' + createNodeLevel.name + '] 的节点吗?', function(index2) {
        layer.prompt({
            formType: 0,
            value: '新节点',
            title: '请输入' + createNodeLevel.name + '名称'
        }, function(name, index3, elem){
            GLOBAL_UTILS.ajaxUtils.ajaxPost(REQUEST_URL.WEB_ELEMENT.addNode
                , {"parent_node_id":treeNode.id, "node_name":name, "node_level": createNodeLevel.value}
                , function(data) {
                    var newNode = data.data;
                    newNode["iconOpen"] = "../../img/element/" + newNode.node_level + "_open.png";
                    newNode["iconClose"] = "../../img/element/" + newNode.node_level + "_close.png";
                    newNode["icon"] = "../../img/element/" + newNode.node_level + "_close.png";
                    newNode["isParent"] = createNodeLevel == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.PAGE ? false : true;
                    zTreeObj.addNodes(treeNode, newNode);
                    layer.msg('创建成功!', {icon:1, time:1800});
                });
            layer.close(index3);
        });
        layer.close(index2);
    });

}

/**
 * 鼠标移开时的显示
 * @returns
 */
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
}
/**
 * 修改名称之前的操作
 * @returns
 */
function beforeEditName(treeId, treeNode) {
    if(treeNode.node_level == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.ROOT.value){//顶层节点不能修改
        layer.msg('不能修改根节点信息!', {time:1800});
        return false;
    }
    beforeNodeName = treeNode.node_name;
    return true;
}

/**
 * 修改名称之后
 * @returns
 */
function onRename(event, treeId, treeNode, isCancel) {
    if(!isCancel && (beforeNodeName != treeNode.node_name)){
        var sendData = {
            node_name:treeNode.node_name,
            id:treeNode.id
        };

        GLOBAL_UTILS.ajaxUtils.ajaxPost(REQUEST_URL.WEB_ELEMENT.editNode, sendData, function(data) {
            layer.msg('修改成功!', {icon:1, time:1800});
        }, function(data) {
            treeNode.node_name = beforeNodeName;
            zTreeObj.updateNode(treeNode);
        });
    }
}

/**
 * 删除之前
 * @returns
 */
function beforeRemove(treeId, treeNode) {
    if(treeNode.node_level == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.ROOT.value){//顶层节点不能删除
        layer.msg('不能删除根节点!', {time:1800});
        return false;
    }
    var x = confirm('确认删除该节点及下属所有节点吗?');
    var flag = true;
    if(x){
        GLOBAL_UTILS.ajaxUtils.ajaxPost(REQUEST_URL.WEB_ELEMENT.delNode, {id: treeNode.id}
            , function(data){
                layer.msg("删除成功!",{icon:1, time:1800});
            }
            , function(data){
                flag = false;
            }, false);
    } else {
        flag = false;
    }

    return flag;
}
/**
 * 删除之后
 * @param event
 * @param treeId
 * @param treeNode
 * @returns
 */
function onRemove(event, treeId, treeNode) {
    //如果是右侧当前的节点被删除了，或者右侧显示的节点在被删除的节点下面，则默认显示第一个页面
    if (currentNode != null
        && ((currentNode.id == treeNode.id)
            || (zTreeObj.getNodeByParam('id', currentNode.id, treeNode) != null))) {
        var node = zTreeObj.getNodesByFilter(filter, true);
        if (node != null) {
            currentNode = node;
            zTreeObj.selectNode(node);
            demoIframe.attr("src","webElement.html?node_id=" + node.id + '&node_name=' + node.node_name);
            demoIframe.click();
        }
    }
}

//判断是否为page类型
function filter(node) {
    return (node.node_level == GLOBAL_PARAM.ELEMENT_NODE_LEVEL.PAGE.value);
}

/**
 * 重新加载Ztree
 * @returns
 */
function refreshZtree() {
    if (zTreeObj != null) {
        zTreeObj.destroy();
        zTreeObj = null;
    }


    GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_ELEMENT.listNode
        , function(data){
            let nodes = data.data;
            $.each(nodes, function(i, n){
                n["iconOpen"] = "../../img/element/" + n.node_level + "_open.png";
                n["iconClose"] = "../../img/element/" + n.node_level + "_close.png";
                n["icon"] = "../../img/element/" + n.node_level + "_close.png";
                n["isParent"] = filter(n) ? false : true ;
            });

            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, nodes);
            demoIframe = parent.$("#element-frame");
            demoIframe.bind("load", loadReady);
            if (currentNode == null) {
                var node = zTreeObj.getNodesByFilter(filter, true);
                if (node != null) {
                    currentNode = node;
                    demoIframe.attr("src","webElement.html?node_id=" + node.id + '&node_name=' + node.node_name);
                    demoIframe.click();
                }
            }
            (currentNode != null) && zTreeObj.selectNode(currentNode);
            zTreeObj.expandAll(true);
        });
}

function loadReady() {
    var bodyH = demoIframe.contents().find("body").get(0).scrollHeight,
        htmlH = demoIframe.contents().find("html").get(0).scrollHeight,
        maxH = Math.max(bodyH, htmlH), minH = Math.min(bodyH, htmlH),
        h = demoIframe.height() >= maxH ? minH:maxH ;
    if (h < 530) h = 530;
    demoIframe.height(h);
}